<template>
    <el-dialog title="选取终端" :visible="visible" @update:visible="updateVisible" @open="init" @closed="doCloseEdit" width="1080px">
        <el-form ref="form" hide-required-asterisk size="mini" :model="form" :show-message="false" label-width="80px">
          <el-form-item label-width="0">
            <el-row>
              <el-col :span="2"><div>终端类型</div></el-col>
              <el-col :span="5">
                <el-select
                  v-model="form.typeId"
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                  @change="selectedType"
                >
                  <el-option
                    v-for="item in typeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label-width="0" class="main">
            <template v-if="form.typeId !== 3">
             <el-row class="rowStyle" v-for="(item, index) in form.terminalArray" :key="index">
              <el-col :span="2"><div>所属城市</div></el-col>
              <el-col :span="5">
                <template v-if="form.typeId == 1">
                  <el-select
                    v-model="form.terminalArray[index].cityArr"
                    multiple
                    collapse-tags
                    :placeholder="$t('请选择')"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="v in cityList"
                      :key="v.id"
                      :label="v.name"
                      :value="v.id"
                    ></el-option>
                  </el-select>
                </template>
                <template v-else>
                  <el-select
                    v-model="form.terminalArray[index].cityId"
                    :placeholder="$t('请选择')"
                    style="width: 100%"
                    @change="selectedCity(form.terminalArray[index].cityId,index)"
                  >
                    <el-option
                      v-for="v in cityList"
                      :key="v.id"
                      :label="v.name"
                      :value="v.id"
                    ></el-option>
                  </el-select>
                </template>
              </el-col>
              <el-col :span="2" :push="1" v-if="form.typeId == 2"><div>区县</div></el-col>
              <el-col :span="5" v-if="form.typeId == 2">
                <template v-if="form.typeId == 2">
                  <el-select
                    v-model="form.terminalArray[index].areaArr"
                    multiple
                    collapse-tags
                    :placeholder="$t('请选择')"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="v in areaList"
                      :key="v.id"
                      :label="v.name"
                      :value="v.id"
                    ></el-option>
                  </el-select>
                </template>
                <template v-else>
                  <el-select
                    v-model="form.terminalArray[index].areaId"
                    :placeholder="$t('请选择')"
                    style="width: 100%"
                    @change="selectedArea"
                  >
                    <el-option
                      v-for="v in areaList"
                      :key="v.id"
                      :label="v.name"
                      :value="v.id"
                    ></el-option>
                  </el-select>
                </template>
              </el-col>
              <el-col :span="3" :push="1"><div>新闻屏幕</div></el-col>
              <el-col :span="5">
                <el-select
                  v-model="form.terminalArray[index].screenId"
                  :placeholder="$t('请选择')"
                  style="width: 100%"
                >
                  <el-option
                    v-for="v in screenList"
                    :key="v.id"
                    :label="v.name"
                    :value="v.id"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="2" style="text-align:center">
                <i v-if="index !== 0" class="el-icon-remove Icon" @click="handleRemove(index)"></i>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col class="add" style="dispaly:flex;">
                <el-button type="primary" @click="handelAdd">添加</el-button>
              </el-col>
            </el-row>

            </template>
            <!-- 定制 -->
            <template v-else>
              <el-row class="rowStyle">
                <el-col :span="2"><div>所属城市</div></el-col>
                <el-col :span="5">
                 <el-select
                    v-model="customize.cityId"
                    :placeholder="$t('请选择')"
                    style="width: 100%"
                    @change="selectedCustomizeCity"
                  >
                    <el-option
                      v-for="item in cityList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="2" :push="1"><div>区县:</div></el-col>
                <el-col :span="5">
                  <el-select
                    v-model="customize.areaId"
                    :placeholder="$t('请选择')"
                    style="width: 100%"
                    @change="selectedCustomize('area')"
                  >
                    <el-option
                      v-for="item in areaList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-col>

                <el-col :span="4" :push="1"><div>新闻屏幕:</div></el-col>
                <el-col :span="5">
                  <el-select
                    v-model="customize.screenId"
                    :placeholder="$t('请选择')"
                    style="width: 100%"
                    @change="selectedCustomize('screen')"
                  >
                    <el-option
                      v-for="item in screenList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <list
                    ref="list"
                    class="center"
                    width="100%"
                    height="430px"
                    :showIndex="true"
                    :list-data="tableData"
                    :table-tag="tableName"
                    :has-select="true"
                    :list-cols="colData"
                    :init-cols-props.sync="initColsProps"
                    :init-headmune-flag="initHeadmuneFlag"
                    :action-opts="actionOpts"
                    @init-table="initTable"
                    @selection-change="handleSelectionChange"
                  >
                    <template slot="onlineSlot" slot-scope="{ row }">
                      {{ row.online | onlineFilter(te) }}
                    </template>
                    <template slot="actionSlot" slot-scope="{ row }">
                      <bs-edit-icon @click.native="handleEditClick(row)"></bs-edit-icon>
                      <bs-delete-icon
                        @click.native="handleDelClick(row)"
                      ></bs-delete-icon>
                    </template>
                  </list>
                  <pagination
                    :total="pageData.total"
                    :page="pageData.page"
                    :limit="pageData.limit"
                    @pagination="getTerminalList"
                    :showAllChecked="true"
                    :allChecked="allSize"
                    @all="handleChangeAllSize"
                  ></pagination>
                </el-col>
              </el-row>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <bs-confirm-button-icon size="mini" @click.native="okClick" :text="'确定'" />
            <bs-cancel-button-icon size="mini" @click.native="doCloseEdit" />
        </div>
    </el-dialog>
</template>

<script>
import { requestOpts } from '@/utils/request.js'
import DeviceApi from '@/api/device'
import NewsApi from '@/api/news'
import Pagination from '@/components/Pagination'
import List from '@/components/List'

export default {
    components:{
      List,
      Pagination

    },
    data() {
        return {
            deviceHeight: 0,
            diyUrl: '',
            // form: {
            //   typeId: 1,
            //   terminalArray: [{
            //     cityId:'',
            //     areaId:'',
            //     screenId:''
            //   }],
            //   reason: ''
            // },
            customize:{
              cityId:'',
              areaId:'',
              screenId:''
            },
            allSize:false,
            selectedCustomizeList: [],
            typeList:[ // 终端类型
              {
                name:'城市',
                id:1,
              },
              {
                name:'区县',
                id:2,
              },
              {
                name:'定制',
                id:3,
              }
            ],
            treeList:[], // 终端分组列表
            cityList:[], // 城市
            areaList:[],// 区县
            screenList:[],
            tableData: [],// 定制列表

            tableName: 'deviceInfoTable',
            actionOpts: {
              show: false,
            },
            initHeadmuneFlag:false,
            initColsProps: [
              'name',
              'no',
              'online',
            ],
            colData: [
              { label: '设备名称', prop: 'name', minwidth: 100 },
              {
                label: '设备id',
                prop: 'no',
                minwidth: 125,
              },
              {
                label: '状态',
                prop: 'online',
                slot: true,
                minwidth: 100,
              },
            ],
            pageData: {
              page: 1,
              total: 0,
              limit: 10,
            },

        }
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        form: {
            type: Object,
            default: () => {}
        },
        id:{
          type:[String,Number],
          default:''
        }
    },
    filters: {
      onlineFilter(val, te) {
        let msg = ''
        switch (val) {
          case 0:
            msg = te('离线')
            break
          case 1:
            msg = te('在线')
            break
        }
        return msg
      },
    },
    methods: {
         te(arg) {
          const hasKey = this.$te(arg)
          if (hasKey) {
            const result = this.$t(arg)
            return result
          }
          return arg
        },
        updateVisible(v) {
            this.$emit('update:visible', v)
        },
        // 关闭
        doCloseEdit() {
            this.updateVisible(false)

            this.clearData()

        },
        // 清空
        clearData(){
          this.form.typeId = 1
          this.form.terminalArray =  [{
            cityArr:[],
            cityId:'',
            areaArr:[],
            areaId:'',
            screenId:''
          }],
          this.customize={
            cityId:'',
            areaId:'',
            screenId:''
          }
        },
        // 初始化
        init() {
          this.getTree()
          this.getTerminalList()
          this.getScreenList()
        },
        initTable(config) {
          this.initHeadmuneFlag = true
        },
        // 获取城市区域
        async getTree(){
          const res = await DeviceApi.loadTree({})
          this.treeList = res.filter(item=>item.id !== '-1')
          let Tree = [];
          this.treeList.forEach(ele => {
            Tree.push({
              id:ele.id,
              name:ele.name
            })
          });
          this.cityList = Tree
        },
        // 获取新闻屏幕
        async getScreenList(){
          const res = await NewsApi.screenList({type:1})
          console.log(res,'getScreenList')
          this.screenList = res || []

        },
        // 获取定制列表
        async getTerminalList(type){
          let ids = new Array(this.customize.areaId ? this.customize.areaId : this.customize.cityId)
          // console.log(ids,'ids..')
          let list = {
            "type": 3,
            "ids": ids,
            "screenId":this.customize.screenId
          }
          var queryData = {
            ...this.queryData,
            ...list
          }
          queryData.current = this.pageData.page
          queryData.size = this.pageData.limit
          const res = await NewsApi.terminalList(queryData)
          if(res){
            this.tableData = res.records || []
            this.pageData.total = Number(res.total ? res.total : 0)

          }
          console.log(res,'获取定制列表')
        },
        // 选择所有页
        handleChangeAllSize(val) {
          this.$refs.list.clearSelection();
          this.allSize = val
        },
        // 定制选择城市
        selectedCustomizeCity(val){
          this.customize.areaId = ''
          this.treeList.forEach(item=>{
            if(item.id == val){
              this.areaList = item.children || []
            }
          })
          if(this.customize.screenId){
            this.getTerminalList("city")
          }
        },
        selectedCustomize(type){

          if(this.customize.cityId  && this.customize.screenId){
            this.getTerminalList(type)
          }
        },
        // 选中城市
        selectedCity(val,selectedIndex){
          this.treeList.forEach(item=>{
            if(item.id == val){
              this.areaList = item.children || []
            }
          })
          // 清空区域
          this.form.terminalArray.forEach((item,index)=>{
            if(val == item.cityId && selectedIndex == index){
              item.areaArr = []
            }
          })
        },
        // 选中屏幕
        selectedScreen(){

        },
        selectedArea(){

        },
        // 多选
        handleSelectionChange(val) {
          this.allSize = false
          console.log('handleSelectionChange========',val)
          this.selectedCustomizeList = val

        },
        // 选中终端类型
        selectedType(val){
          console.log(val,'val....======')
          this.form.typeId = val
          this.form.terminalArray = [{
              cityId:'',
              areaId:'',
              screenId:''
            }]

        },
        handelAdd(){
          this.form.terminalArray.push({
            cityId:'',
            cityArr:[],
            areaArr:[],
            screenId:''
          })
        },
        handleRemove(index){
          this.form.terminalArray.splice(index,1)
        },
        validate(){
          let isValidate = true
          if(this.form.typeId == 1){
            this.form.terminalArray.forEach(item=>{
              if(item.cityArr.length == 0 || item.screenId == ''){
                isValidate = false
              }
            })

          }else if(this.form.typeId == 2){
            this.form.terminalArray.forEach(item=>{
              if(item.areaArr.length == 0 || item.screenId == ''){
                isValidate = false
              }
            })
          }else if(this.form.typeId == 3){
            if(!this.customize.cityId || !this.customize.screenId ){
              isValidate = false
            }
          }
          return isValidate
        },

        async okClick(){
          console.log(this.form,'this.form...')
          if(!this.validate()){
            return this.$message('请填写完整信息')
          }
          let terminals = [];
          // 终端类型为城市
          if(this.form.typeId == 1){
            terminals = this.form.terminalArray.map(v=>{
              v.ids = v.cityArr
              delete v.areaArr
              delete v.cityId
              delete v.cityArr
              delete v.areaId
              return v
            })
          }
          // 终端类型为区域
          if(this.form.typeId == 2){
            terminals = this.form.terminalArray.map(v=>{
              v.ids = v.areaArr
              delete v.areaArr
              delete v.cityId
              delete v.cityArr
              delete v.areaId
              return v
            })
          }
          // 终端类型为定制
          if(this.form.typeId == 3){
            let ids = []
            console.log(this.selectedCustomizeList,'this.selssssss')
            this.selectedCustomizeList.forEach(item=>{
              ids.push(item.id)
            })
            if(this.allSize){
              // allSelected.push(this.customize.areaId ? this.customize.areaId : this.customize.cityId)
              terminals = {
                "screenId":this.customize.screenId,
                "ids":new Array(this.customize.areaId ? this.customize.areaId : this.customize.cityId),
              }
            }else{
              terminals = {
                "screenId":this.customize.screenId,
                "ids":new Array(this.customize.areaId ? this.customize.areaId : this.customize.cityId),
                "terminalIds":ids
              }
            }
          }
          let params={
            type:this.form.typeId,
            terminals:terminals,
            newsNo:this.id,
          }
          const res = await NewsApi.saveTerminal(params)
          if(res){
            this.$message.success('添加成功')
            this.updateVisible(false)
          }
        }
    }
}
</script>

<style scoped>
.main{
  height: 520px;
  overflow-y: scroll;
  overflow-x: hidden;
}
.add{
  display: flex;
  flex-direction: row;
  justify-content: center;

}
.rowStyle{
	margin-bottom: 10px;
}
::v-deep .el-dialog {
    height: 700px;
}
::v-deep .el-form {
    margin: 15px 15px 0 15px !important;
}
</style>
